<template>
  <div :class="{'mobile-detail-wrap':showMobilePage}" class="customer-container">
    <div class="title">
      <div><Title title="结算统计" font-size="16px"/></div>
      <div style="flex:1;"/>
    </div>
    <div :class="{'mobile-el-form': showMobilePage}">
      <settleAccountsInfo :detail-data="detailData" :is-mobile="showMobilePage" :loading="loading" />
    </div>
    <div class="title">
      <div style="flex: 1;">
        <Title title="结算表单" font-size="16px"/>
      </div>
      <div class="btn-right" style="align-items: center;display: flex;">
        <el-button v-if="hasRouteAuth('mengli:settleAccountsLog:refresh')" :loading="refreshLoading" style="margin-right: 10px;" type="primary" size="small" @click="handleRefresh">刷新</el-button>
        <btnGroup
          v-if="hasRouteAuth('mengli:settleAccountsLog:export')"
          ref="btnGroupRef"
          :list="[
            { label:'导出', exportApi:'/admin/mengli/settleAccountsLog/detail/export', exportName:'结算记录', beforeExport: beforeExport, type: 'export', auth: hasRouteAuth('mengli:settleAccountsLog:export') },
          ]"
        />
      </div>
    </div>
    <div v-loading="loading">
      <el-table
        v-if="list.items.length > 0"
        ref="customerTableRef"
        :data="list.items"
        :row-height="49"
        :height="setTableHeight - 123"
        :summary-method="getSummaries"
        show-summary
        use-virtual
        class="fb-table"
        element-loading-text="加载中..."
        empty-text="暂无数据"
        header-cell-class-name="order-data-header-cell"
        fit
        border
        style="margin-bottom: 20px;"
        hightlight-current-row>
        <el-table-column :fixed="showMobilePage?false:'left'" align="left" label="序号" width="60">
          <template slot-scope="scope">
            <ToolTip :content="scope.row.i"/>
          </template>
        </el-table-column>
        <el-table-column align="left" label="关联合同" width="90">
          <template slot-scope="scope">
            <div class="ellipsis link" @click="toLegal(scope.row)">查看</div>
          </template>
        </el-table-column>
        <el-table-column align="left" label="仓库" min-width="120">
          <template slot-scope="scope">
            <ToolTip :content="scope.row.repositoryName"/>
          </template>
        </el-table-column>
        <el-table-column align="left" label="供应商" min-width="120">
          <template slot-scope="scope">
            <ToolTip :content="scope.row.supplier" is-can-click @handelClick="toMengliSuppliers(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column align="left" label="IP" min-width="120">
          <template slot-scope="scope">
            <ToolTip :content="scope.row.ipName"/>
          </template>
        </el-table-column>
        <el-table-column align="left" label="SKU编码" min-width="150">
          <template slot-scope="scope">
            <ToolTip :content="scope.row.code" is-can-click @handelClick="toInventoryDetail(scope.row.id)" />
          </template>
        </el-table-column>
        <el-table-column align="left" label="标题" min-width="120">
          <template slot-scope="scope">
            <ToolTip :content="scope.row.title"/>
          </template>
        </el-table-column>
        <el-table-column label="期初实际">
          <el-table-column align="left" label="数量" min-width="120">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.startActual.count"/>
            </template>
          </el-table-column>
          <el-table-column align="left" label="成本(元)" min-width="120">
            <template slot-scope="scope">
              <PriceColumn :real-val="scope.row.startActual.cost" :price="scope.row.startActual.cost" />
            </template>
          </el-table-column>
          <el-table-column align="left" label="金额(元)" min-width="120">
            <template slot-scope="scope">
              <PriceColumn :real-val="scope.row.startActual.amount" :price="scope.row.startActual.amount" />
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="入库合计">
          <el-table-column align="left" label="入库数量" min-width="120">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.stockInTotal.inventoryCount"/>
            </template>
          </el-table-column>
          <el-table-column align="left" label="成本(元)" min-width="120">
            <template slot-scope="scope">
              <PriceColumn :real-val="scope.row.stockInTotal.inventoryCost" :price="scope.row.stockInTotal.inventoryCost" />
            </template>
          </el-table-column>
          <el-table-column align="left" label="金额(元)" min-width="120">
            <template slot-scope="scope">
              <PriceColumn :real-val="scope.row.stockInTotal.inventoryAmount" :price="scope.row.stockInTotal.inventoryAmount" />
            </template>
          </el-table-column>
          <el-table-column align="left" label="淘宝退货入库" min-width="120">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.stockInTotal.taobaoCount"/>
            </template>
          </el-table-column>
          <el-table-column align="left" label="成本(元)" min-width="120">
            <template slot-scope="scope">
              <PriceColumn :real-val="scope.row.stockInTotal.taobaoCost" :price="scope.row.stockInTotal.taobaoCost" />
            </template>
          </el-table-column>
          <el-table-column align="left" label="金额(元)" min-width="120">
            <template slot-scope="scope">
              <PriceColumn :real-val="scope.row.stockInTotal.taobaoAmount" :price="scope.row.stockInTotal.taobaoAmount" />
            </template>
          </el-table-column>
          <el-table-column align="left" label="其他" min-width="120">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.stockInTotal.otherCount"/>
            </template>
          </el-table-column>
          <el-table-column align="left" label="成本(元)" min-width="120">
            <template slot-scope="scope">
              <PriceColumn :real-val="scope.row.stockInTotal.otherCost" :price="scope.row.stockInTotal.otherCost" />
            </template>
          </el-table-column>
          <el-table-column align="left" label="金额(元)" min-width="120">
            <template slot-scope="scope">
              <PriceColumn :real-val="scope.row.stockInTotal.otherAmount" :price="scope.row.stockInTotal.otherAmount" />
            </template>
          </el-table-column>
          <el-table-column align="left" label="盘盈" min-width="120">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.stockInTotal.surplus"/>
            </template>
          </el-table-column>
          <el-table-column align="left" label="金额(元)" min-width="120">
            <template slot-scope="scope">
              <PriceColumn :real-val="scope.row.stockInTotal.surplusAmount" :price="scope.row.stockInTotal.surplusAmount" />
            </template>
          </el-table-column>
          <el-table-column align="left" label="总金额(元)" min-width="120">
            <template slot-scope="scope">
              <PriceColumn :real-val="scope.row.stockInTotal.sum" :price="scope.row.stockInTotal.sum" />
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="出库合计">
          <el-table-column align="left" label="电商销售" min-width="120">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.stockOutTotal.commerceCount"/>
            </template>
          </el-table-column>
          <el-table-column align="left" label="金额(元)" min-width="120">
            <template slot-scope="scope">
              <PriceColumn :real-val="scope.row.stockOutTotal.commerceAmount" :price="scope.row.stockOutTotal.commerceAmount" />
            </template>
          </el-table-column>
          <el-table-column align="left" label="商户客户" min-width="120">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.stockOutTotal.merchantCustomerCount"/>
            </template>
          </el-table-column>
          <el-table-column align="left" label="金额(元)" min-width="120">
            <template slot-scope="scope">
              <PriceColumn :real-val="scope.row.stockOutTotal.merchantCustomerAmount" :price="scope.row.stockOutTotal.merchantCustomerAmount" />
            </template>
          </el-table-column>
          <el-table-column align="left" label="销售-招待" min-width="120">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.stockOutTotal.salesCount"/>
            </template>
          </el-table-column>
          <el-table-column align="left" label="金额(元)" min-width="120">
            <template slot-scope="scope">
              <PriceColumn :real-val="scope.row.stockOutTotal.salesAmount" :price="scope.row.stockOutTotal.salesAmount" />
            </template>
          </el-table-column>
          <el-table-column align="left" label="管理-办公" min-width="120">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.stockOutTotal.manageCount"/>
            </template>
          </el-table-column>
          <el-table-column align="left" label="金额(元)" min-width="120">
            <template slot-scope="scope">
              <PriceColumn :real-val="scope.row.stockOutTotal.manageAmount" :price="scope.row.stockOutTotal.manageAmount" />
            </template>
          </el-table-column>
          <el-table-column align="left" label="销售-宣传推广" min-width="120">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.stockOutTotal.promoteCount"/>
            </template>
          </el-table-column>
          <el-table-column align="left" label="金额(元)" min-width="120">
            <template slot-scope="scope">
              <PriceColumn :real-val="scope.row.stockOutTotal.promoteAmount" :price="scope.row.stockOutTotal.promoteAmount" />
            </template>
          </el-table-column>
          <el-table-column align="left" label="摩点" min-width="120">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.stockOutTotal.frictionPointCount"/>
            </template>
          </el-table-column>
          <el-table-column align="left" label="金额(元)" min-width="120">
            <template slot-scope="scope">
              <PriceColumn :real-val="scope.row.stockOutTotal.frictionPointAmount" :price="scope.row.stockOutTotal.frictionPointAmount" />
            </template>
          </el-table-column>
          <el-table-column align="left" label="内购" min-width="120">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.stockOutTotal.inAppPurchaseCount"/>
            </template>
          </el-table-column>
          <el-table-column align="left" label="金额(元)" min-width="120">
            <template slot-scope="scope">
              <PriceColumn :real-val="scope.row.stockOutTotal.inAppPurchaseAmount" :price="scope.row.stockOutTotal.inAppPurchaseAmount" />
            </template>
          </el-table-column>
          <el-table-column align="left" label="北京银行" min-width="120">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.stockOutTotal.bankOfBeijingCount"/>
            </template>
          </el-table-column>
          <el-table-column align="left" label="金额(元)" min-width="120">
            <template slot-scope="scope">
              <PriceColumn :real-val="scope.row.stockOutTotal.bankOfBeijingAmount" :price="scope.row.stockOutTotal.bankOfBeijingAmount" />
            </template>
          </el-table-column>
          <el-table-column align="left" label="其他" min-width="120">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.stockOutTotal.otherCount"/>
            </template>
          </el-table-column>
          <el-table-column align="left" label="金额(元)" min-width="120">
            <template slot-scope="scope">
              <PriceColumn :real-val="scope.row.stockOutTotal.otherAmount" :price="scope.row.stockOutTotal.otherAmount" />
            </template>
          </el-table-column>
          <el-table-column align="left" label="盘亏" min-width="120">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.stockOutTotal.lossCount"/>
            </template>
          </el-table-column>
          <el-table-column align="left" label="金额(元)" min-width="120">
            <template slot-scope="scope">
              <PriceColumn :real-val="scope.row.stockOutTotal.lossAmount" :price="scope.row.stockOutTotal.lossAmount" />
            </template>
          </el-table-column>
          <el-table-column align="left" label="成本价(元)" min-width="120">
            <template slot-scope="scope">
              <PriceColumn :real-val="scope.row.stockOutTotal.cost" :price="scope.row.stockOutTotal.cost" />
            </template>
          </el-table-column>
          <el-table-column align="left" label="总金额(元)" min-width="120">
            <template slot-scope="scope">
              <PriceColumn :real-val="scope.row.stockOutTotal.sum" :price="scope.row.stockOutTotal.sum" />
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column :fixed="showMobilePage?false:'right'" label="期末实际" align="left" width="300">
          <el-table-column align="left" label="数量" min-width="100">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.endActual.count"/>
            </template>
          </el-table-column>
          <el-table-column align="left" label="成本(元)" min-width="100">
            <template slot-scope="scope">
              <PriceColumn :real-val="scope.row.endActual.cost" :price="scope.row.endActual.cost" />
            </template>
          </el-table-column>
          <el-table-column align="left" label="金额(元)" min-width="100">
            <template slot-scope="scope">
              <PriceColumn :real-val="scope.row.endActual.amount" :price="scope.row.endActual.amount" />
            </template>
          </el-table-column>
        </el-table-column>
      </el-table>
      <empty-placeholder v-else-if="!list.isInit" style="margin-bottom: 24px" />
    </div>
    <fixed-pagination>
      <span style="flex:1;"/>
      <el-pagination
        v-show="list.total > 0"
        :current-page="list.page"
        :page-size="list.perPage"
        :total="list.total"
        :page-sizes="[20, 50, 100, 250, 500]"
        :layout="showMobilePage?'total, prev, next, jumper':'total, prev, pager, next, sizes, jumper'"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </fixed-pagination>
  </div>
</template>

<script>
import Title from '@/components/Title';
import settleAccountsInfo from './settleAccountsInfo';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import TableAdaptive from '@/mixins/tableAdaptive';
import { hasRouteAuth } from '@/utils/permission';
import { getSettleAccountsDetail, refreshSettleAccounts } from '@/api/mengli';
import btnGroup from '@/components/Common/baseComponent/btnGroup';
import { mapState } from 'vuex';

export default {
  components: {
    Title,
    btnGroup,
    settleAccountsInfo,
    EmptyPlaceholder
  },
  mixins: [TableAdaptive],
  data() {
    return {
      loading: false,
      refreshLoading: false,
      settleAccountsId: null,
      detailData: { // 结算统计
        month: '',
        createTime: '',
        creator: '',
        creatorUserId: null,
        status: null
      },
      page: 1,
      perPage: 20,
      list: { // 结算表单
        items: [],
        page: 1,
        perPage: 20,
        total: 0,
        isInit: true,
        totalInfo: {} // 合计行
      },
      totalInfoMap: {
        '7': 'startActual',
        '9': 'startAmount',
        '10': 'inventoryCount',
        '12': 'inventoryAmount',
        '13': 'taobaoCount',
        '15': 'taobaoAmount',
        '16': 'otherCountIn',
        '18': 'otherAmountIn',
        '19': 'surplusCount',
        '20': 'surplusAmount',
        '21': 'stockInAmount',
        '22': 'commerceCount',
        '23': 'commerceAmount',
        '24': 'merchantCustomerCount',
        '25': 'merchantCustomerAmount',
        '26': 'salesCount',
        '27': 'salesAmount',
        '28': 'manageCount',
        '29': 'manageAmount',
        '30': 'promoteCount',
        '31': 'promoteAmount',
        '32': 'frictionPointCount',
        '33': 'frictionPointAmount',
        '34': 'inAppPurchaseCount',
        '35': 'inAppPurchaseAmount',
        '36': 'bankOfBeijingCount',
        '37': 'bankOfBeijingAmount',
        '38': 'otherCountOut',
        '39': 'otherAmountOut',
        '40': 'lossCount',
        '41': 'lossAmount',
        '43': 'stockOutAmount',
        '44': 'endActual',
        '46': 'endAmount'
      }
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    })
  },
  created() {
    this.settleAccountsId = Number(this.$route.params.id) || null;
    this.fetchData(true);
  },
  methods: {
    hasRouteAuth,
    fetchData(reset = false) {
      if (reset) this.page = 1;
      const params = {
        page: this.page,
        perPage: this.perPage
      };
      this.loading = true;
      getSettleAccountsDetail(this.settleAccountsId, params).then(res => {
        if (res.code === 200 && res.data) {
          const { statisticsInfo, formInfo } = res.data;
          this.detailData = statisticsInfo;
          this.list = formInfo;
          this.loading = false;
        }
      }, result => {
        this.loading = false;
      }).catch(err => {
        console.error(err);
        this.$message({ type: 'error', message: err.message });
      });
    },
    getSummaries(param) {
      const { columns } = param;
      const sums = [];
      columns.forEach((_, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        const prop = this.totalInfoMap[index];
        if (prop) {
          // 金额保留两位小数
          const isAmount = prop.includes('Amount');
          sums[index] = isAmount ? this.list.totalInfo[prop].toFixed(2) : this.list.totalInfo[prop];
        }
      });
      return sums;
    },
    handleRefresh() {
      this.refreshLoading = true;
      this.loading = true;
      const params = {
        page: this.page,
        perPage: this.perPage
      };
      refreshSettleAccounts(this.settleAccountsId, params).then(res => {
        if (res.code === 200 && res.data) {
          const { statisticsInfo, formInfo } = res.data;
          this.detailData = statisticsInfo;
          this.list = formInfo;
          this.loading = false;
          this.refreshLoading = false;
          this.$message({ type: 'success', message: '刷新成功' });
        }
      }, result => {
        this.loading = false;
        this.refreshLoading = false;
      }).catch(err => {
        console.error(err);
        this.$message({ type: 'error', message: err.message });
      });
    },
    toLegal(row) {
      const url = this.$router.resolve({
        name: 'ContractManagement',
        query: { oppCompany: row.supplier }
      });
      window.open(url.href, '_blank');
    },
    toMengliSuppliers(row) {
      const url = this.$router.resolve({
        name: 'mengliSuppliers',
        query: { keyword: row.supplier }
      });
      window.open(url.href, '_blank');
    },
    toInventoryDetail(id) {
      const url = this.$router.resolve({
        name: 'mengliInventoryDetail',
        params: { id }
      });
      window.open(url.href, '_blank');
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.fetchData(true);
      this.$nextTick(() => {
        document.body.scrollTop = document.documentElement.scrollTop = 0;
      });
    },
    handleCurrentChange(toPage) {
      this.page = toPage;
      this.fetchData();
      this.$nextTick(() => {
        document.body.scrollTop = document.documentElement.scrollTop = 0;
      });
    },
    beforeExport() {
      const params = {
        id: this.settleAccountsId
      };
      if (this.$refs.btnGroupRef) {
        this.$refs.btnGroupRef.btnExport(params);
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.link {
  color: #406eff;
  cursor: pointer;
}
.customer-container {
  min-height: calc(100vh - 53px - 32px);
  margin: 16px;
  background-color: #fff;
  padding: 20px;
  box-sizing: border-box;
  &.mobile-detail-wrap {
    margin: 0;
    padding: 20px 12px 40px 12px;
  }
  .title {
    display:flex;
    align-items:center;
    margin-bottom: 10px;
  }
}
::v-deep {
  .el-table:not(.default-scroll-table) .el-table__fixed,
  .el-table:not(.default-scroll-table) .el-table__fixed-right {
    height: 100% !important;
  }
}
</style>
